package com.xiaotu.service.Impl;

import com.xiaotu.po.Image;
import com.xiaotu.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {
    @Value("${file.path}")
    private String filePath;
    @Value("${file.url}")
    private String fileUrl;
    private static Set<String> imageType=new HashSet<>();
    static {
        imageType.add(".jpg");
        imageType.add(".png");
        imageType.add(".gif");
        imageType.add(".pdf");
    }
    @Override
    public Image upload(MultipartFile file) {
        String filename = file.getOriginalFilename();//获取文件全名
        filename.toLowerCase();//将文件名转换为小写
        //获取后缀名
        int i = filename.lastIndexOf(".");
        String fileType = filename.substring(i);//后缀名
        //判断文件类型是否为图片
        if(!imageType.contains(fileType)){
            return Image.fail();
        }
        //判断用户上传的是否为恶意程序.高度和宽度是否为null
        try{
            BufferedImage read = ImageIO.read(file.getInputStream());
            int width = read.getWidth();
            int height = read.getHeight();
            if(width==0||height==0){
                return Image.fail();
            }
            //采用分目录存储方式
            //时间存储
            String format = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            //准备存储的目录
            String fileDir = filePath + format;//目录路径
            String fileurl = fileUrl+format;//虚拟路径
            File f = new File(fileDir);
            if(!f.exists()){
                f.mkdirs();
            }
            //实现文件上传
            //动态拼接文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String NewFileName = uuid+fileType;
            //文件上传的全路径 磁盘地址+新文件名
            String url = fileDir+NewFileName;
            file.transferTo(new File(url));
            return Image.success(fileurl+NewFileName,width,height);
        }catch (Exception e){
            e.printStackTrace();
            return Image.fail();
        }
    }
}
